import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutterApp/main.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class HttpManager {
  factory HttpManager() => _getInstance();
  static HttpManager _instance;

  Dio get http => _dio;
  Dio _dio;

  static const int CONNECT_TIMEOUT = 50000;
  static const int RECEIVE_TIMEOUT = 30000;

  static _getInstance() {
    if (_instance == null) {
      _instance = HttpManager._();
    }
    return _instance;
  }

  // 初始化
  HttpManager._() {
    var options = BaseOptions(
        connectTimeout: CONNECT_TIMEOUT, receiveTimeout: RECEIVE_TIMEOUT);

    _dio = Dio(options)..interceptors.add(LogInterceptor());
    //添加拦截器
    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
      String loadingMmessage = options.extra['loadingMessage'];
      if (loadingMmessage != '') {
        EasyLoading.instance
          ..contentPadding = EdgeInsets.symmetric(
            vertical: 15.0,
            horizontal: 30.0,
          )
          ..fontSize=15.0;
          
        EasyLoading.show(
            status: loadingMmessage, maskType: EasyLoadingMaskType.clear);
      }
      return options;
    }, onResponse: (Response response) {
      var result = {"isCorrect": true, "data": response.data['data']};
      EasyLoading.dismiss();
      if (response.data['code'] != "200") {
        result['isCorrect'] = false;
        showOkAlertDialog(
            context: navigatorKey.currentState.overlay.context,
            title: response.data['message']);
      }
      return result;
    }, onError: (DioError e) {
      EasyLoading.dismiss();

      return e;
    }));
  }
}
